﻿using System;
using System.Linq;
using System.Reflection;

namespace EOrm
{
    /// <summary>
    /// 实体映射
    /// </summary>
    public static class EOrmEntityMapper
    {
        /// <summary>
        /// 实体类型映射
        /// </summary>
        /// <param name="type">实体类型</param>
        /// <param name="columnName">列名</param>
        /// <exception cref="Exception">实体配置缺少对应项目</exception>
        public static PropertyInfo EntityTypeMap(Type type, string columnName)
        {
            string propName = columnName.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries)
                                           .Select((t, i) => i == 0 ? t.ToLower() : t.Substring(0, 1).ToUpper() + t.Substring(1))
                                           .Aggregate((a, b) => a + b);
            PropertyInfo prop = type.GetProperty(propName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
            if (prop == null)
            {
                prop = type.GetProperty(columnName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
            }
            if (prop == null)
            {
                throw new Exception($@"没有属性：{propName}或{columnName}");
            }
            return prop;
        }
    }
}
